<?php
/**
 * Prado Portal.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: DownloadPortlet.php 289 2008-11-14 05:34:40Z steen.rabol@gmail.com $
 *
 */

Prado::using('Application.Portlets.Portlet');
Prado::using('Application.Portlets.DownloadPortlet.Common.DownloadPortletGrpRecord');
Prado::using('Application.Portlets.DownloadPortlet.Common.DownloadPortletFileRecord');

class DownloadPortlet extends Portlet
{
	private	$_savePath;

	public function onInit($p)
	{
		$this->_savePath	= $this->Application->PortalBasePath	. '/storage/DownloadPortlet/';
		PortalUtil::CreateDirStructure($this->_savePath);
		parent::onInit($p);
	}

	public function onLoad($param)
	{
		parent::onLoad($param);
		if(!$this->Page->IsPostBack)
		{
			$this->bindData();
		}
	}

	public function bindData()
	{
		$dr	= $this->DataAccess->createCommand("select * from tbldownloadportletgrps where active=1")->query();
		$grps = $dr->readAll();
		if(count($grps) >= 3)
		{
			$this->GroupDataList->RepeatColumns = 3;
		}
		else
		{
			$this->GroupDataList->RepeatColumns = 2;
		}

		$this->GroupDataList->DataSource = $grps;
		$this->GroupDataList->dataBind();
	}

	public function getDownloadGroupsData()
	{
		return $this->DataAccess->createCommand("select * from tbldownloadportletgrps order by name")->query();
	}

	public function onItemCommand($s,$p)
	{
		switch($p->CommandName)
		{
			case "ShowContent":
				$grpid = $p->CommandParameter;
				$this->FilesDataList->DataSource=$this->DataAccess->createCommand("select * from tbldownloadfiles where active=1 && grpid=$grpid order by filedate desc")->query();
				$this->FilesDataList->dataBind();
				$grpRow	= $this->DataAccess->createCommand("select * from tbldownloadportletgrps where id=$grpid")->queryRow();
				$this->pnlFiles->GroupingText 	= "Available files in : " . $grpRow['name'];
				$this->grpDescription->Text		= $grpRow['description'];
				break;

			case "SendFile":
				$fileid		= $p->CommandParameter;
				$file		= $this->DataAccess->createCommand("select * from tbldownloadfiles where id=$fileid")->queryRow();
				$filename	= $this->_savePath . $file['filename'];
				if(!file_exists($filename))
				{
					$this->Page->reportError(1,Prado::localize("The requested file is not available!"));
				}
				$sql = "update tbldownloadfiles set dlcount=dlcount+1 where id=$fileid";
				$this->DataAccess->createCommand($sql)->execute();
				$sql = "select * from tbldownloadfiles where active=1 && grpid=" . $file['grpid'];
				$s->DataSource=$this->DataAccess->createCommand($sql)->query();
				$s->dataBind();
				$this->Response->writeFile($filename);
				break;
		}
	}
}
?>